from PyQt5.QtWidgets import QWidget
import cv2
from src.config import config
from src.views.setting import *
from src.common.utils.serial.SerialUtil import SerialUtil
from src.common.utils.http.httpUtil import HttpUtil
http = HttpUtil("http://")
serial = SerialUtil()


class UISettingView(QWidget, Ui_Form):
    def __init__(self):
        super(UISettingView, self).__init__()
        self.setupUi(self)
        self.initParams()
        self.initSlot()
        self.initUi()

    def initParams(self):
        self.message = QtWidgets.QMessageBox  # 初始化消息弹框，information消息，critical失败
        self.bpsList = ["0", "9600", "115200"]
        if str(config.serial.bps) in self.bpsList:
            self.bpsList.remove("0")
        else:
            self.bpsList[0] = str(config.serial.bps)

    def initUi(self):
        self.lineEdit.setText(str(config.camera.url))
        self.lineEdit_2.setText(str(config.camera.screenShotPath))
        self.lineEdit_3.setText(str(config.camera.fps))

        self.comboBox.clear()
        portList = []
        for item in serial.getPortList():
            portList.append(item[0])
        if not portList:
            portList = ["未检测到串口"]
        self.comboBox.addItems(portList)
        if str(config.serial.port) in portList: self.comboBox.setCurrentText(str(config.serial.port))
        # self.comboBox.addItem(str(config.serial.port))
        self.comboBox_2.clear()
        self.comboBox_2.addItems(self.bpsList)
        self.comboBox_2.setCurrentText(str(config.serial.bps))
        self.lineEdit_4.setText(str(config.serial.timeout))
        if config.serial.readType == "len":
            self.comboBox_3.setCurrentIndex(0)
        elif config.serial.readType == "line":
            self.comboBox_3.setCurrentIndex(1)
        self.lineEdit_5.setText(str(config.serial.readLen))
        self.lineEdit_6.setText(str(config.serial.readLine))

        self.lineEdit_7.setText(str(config.server.ip))
        self.lineEdit_8.setText(str(config.server.port))

    def initSlot(self):
        self.pushButton.clicked.connect(self.selectPath)
        self.pushButton_2.clicked.connect(self.reset)
        self.pushButton_4.clicked.connect(self.check)
        self.pushButton_3.clicked.connect(self.save)

    def selectPath(self):
        """
        选择文件保存路径
        :return:
        """
        directory = QtWidgets.QFileDialog.getExistingDirectory(None, "选择文件夹", "/")
        if not directory: return
        self.lineEdit_2.setText(directory+'/')

    def reset(self):
        res = self.message.question(self, "询问", "是否重置当前配置", self.message.Yes | self.message.No)
        if (res == self.message.No):
            return

        self.initParams()
        self.initUi()
        self.message.information(self, "提示", "重置当前配置成功", self.message.Ok)

    def check(self):
        res = self.message.question(self, "询问", "是否检查当前配置可用性", self.message.Yes | self.message.No)
        if (res == self.message.No):
            return

        cameraUrl = self.lineEdit.text()
        try:
            cameraUrl = int(cameraUrl)

            cap = cv2.VideoCapture(cameraUrl)  # 初始化摄像头
            if cap.isOpened():
                print("摄像头可用")
                self.message.information(self, "提示", "摄像头可用", self.message.Ok)
            else:
                print("摄像头不可用")
                self.message.critical(self, "提示", "摄像头不可用", self.message.Ok)
        except:
            if ('rtsp://' or 'rtmp://') and '@' in cameraUrl:
                url = cameraUrl.split('@')[1].split('/')[0]

                rst = http.get(url, timeout=3)
                if rst:
                    print("網絡摄像头可用")
                    self.message.information(self, "提示", "網絡摄像头可用", self.message.Ok)
                else:
                    print("网络摄像头不可用")
                    self.message.critical(self, "提示", "网络摄像头不可用", self.message.Ok)


        port = self.comboBox.currentText()
        bps = int(self.comboBox_2.currentText())
        timeout = float(self.lineEdit_4.text())
        if serial.open(port, bps, timeout):
            print("串口可用")
            serial.close()
            self.message.information(self, "提示", "串口可用", self.message.Ok)
        else:
            print("串口当前不可用")
            self.message.critical(self, "提示", "串口不可用", self.message.Ok)

        ip = self.lineEdit_7.text()
        port = self.lineEdit_8.text()
        url = f"{ip}:{port}/websocket/ping"
        rst = http.get(url)
        if rst == '2114':
            print("网络通信可用")
            self.message.information(self, "提示", "网络通信可用", self.message.Ok)
        else:
            print("网络通信不可用")
            self.message.critical(self, "提示", "网络通信不可用", self.message.Ok)


    def save(self):
        res = self.message.question(self, "询问", "是否保存当前配置", self.message.Yes | self.message.No)
        if (res == self.message.No):
            return

        datas = {}
        cameraConfig = {}
        try:
            cameraConfig['url'] = int(self.lineEdit.text())
        except:
            cameraConfig['url'] = self.lineEdit.text()

        cameraConfig['screenShotPath'] = self.lineEdit_2.text()
        cameraConfig['fps'] = int(self.lineEdit_3.text())

        serialConfig = {}
        serialConfig['port'] = self.comboBox.currentText()
        serialConfig['bps'] = int(self.comboBox_2.currentText())
        serialConfig['timeout'] = float(self.lineEdit_4.text())
        if (self.comboBox_3.currentIndex()):
            serialConfig['readType'] = 'line'
        else:
            serialConfig['readType'] = 'len'
        serialConfig['readLen'] = int(self.lineEdit_5.text())
        serialConfig['readLine'] = int(self.lineEdit_6.text())

        serverConfig = {}
        serverConfig['ip'] = self.lineEdit_7.text()
        serverConfig['port'] = int(self.lineEdit_8.text())

        datas['camera'] = cameraConfig
        datas['serial'] = serialConfig
        datas['server'] = serverConfig

        config.write(datas)

        self.message.information(self, "提示", "保存当前配置成功", self.message.Ok)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    ui = UISettingView()
    ui.show()
    sys.exit(app.exec_())